package com.aier.service.purchase;

import com.aier.bean.common.CommonResult;
import com.aier.bean.purchase.GoodsArrivedBean;
import com.aier.bean.purchase.PurchaseBean;
import com.aier.bean.purchase.PurchaseExcelBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采购信息excel相关的service
 */
@Service
public class PurchaseExcelService {
    @Resource
    private PurchaseService purchaseService;

    @Resource
    private GoodsArrivedService goodsArrivedService;


    /**
     * 构建采购信息excel的内容
     *
     * @return
     */
    public Map<String, List<PurchaseExcelBean>> buildPurchaseInfoExcel() {
        String sheetName = "采购信息";
        /** 获取所有的采购信息 **/
        List<PurchaseBean> purchaseBeanList = purchaseService.getAllPurchase();
        List<PurchaseExcelBean> purchaseExcelBeanList = new ArrayList<>();
        purchaseBeanList.stream().forEach(purchaseBean -> {
            PurchaseExcelBean purchaseExcelBean = new PurchaseExcelBean();
            purchaseExcelBean.setModelName(purchaseBean.getModelName());
            purchaseExcelBean.setContractCode(purchaseBean.getContractCode());
            purchaseExcelBean.setSalesperson(purchaseBean.getSalesperson());
            purchaseExcelBean.setOrderQty(purchaseBean.getOrderQty());
            /** 根据合同编号获取到货信息 **/
            List<GoodsArrivedBean> goodsArrivedBeanList = goodsArrivedService.getGoodsArrivedByContractCode(purchaseBean.getContractCode());
            /** 算出合同编号对应的 已 到货数量 **/
            int arrivedQty = goodsArrivedBeanList.stream().mapToInt(GoodsArrivedBean::getArrivedQty).sum();
            purchaseExcelBean.setArrivedQty(arrivedQty);
            /** 剩余未到货数量 = 下单数量-已到货总数 **/
            purchaseExcelBean.setRemainingQty(purchaseBean.getOrderQty() - arrivedQty);
            purchaseExcelBeanList.add(purchaseExcelBean);
        });
        Map<String, List<PurchaseExcelBean>> result = new HashMap<>();
        result.put(sheetName,purchaseExcelBeanList);
        return result;
    }

    /**
     * 结束合同（订单完成）
     */
    public CommonResult endContractCode(String contractCode){
        purchaseService.endContractCode(contractCode);
        return CommonResult.success();
    }
}
